package demo8;

/**
 * 二叉树中的深搜_二叉树剪枝
 * https://leetcode.cn/problems/binary-tree-pruning/
 */
class Solution1 {
    public TreeNode pruneTree(TreeNode root) {
        int ret = dfs(root);
        return ret == 0 ? null : root;
    }

    private int dfs(TreeNode root) {
        // 出口, 叶子节点就无需继续
        if (root.left == null && root.right == null) return root.val;

        int left = 0, right = 0;
        if(root.left != null) {
            left = dfs(root.left);
            if(left == 0) root.left = null;
        }
        if(root.right != null) {
            right = dfs(root.right);
            if(right == 0) root.right = null;
        }
        return left + right + root.val;
    }
}